package net.oschina.dajiangnan.wx.process.mp.tools;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import net.oschina.dajiangnan.wx.util.SecretUtil;
import org.apache.commons.lang3.StringUtils;

import net.oschina.dajiangnan.wx.constants.Config;


public class SignatureValid {

    public static boolean valid(String signature,String timestamp,String nonce){
        
        if(!StringUtils.isEmpty(signature) &&
                !StringUtils.isEmpty(timestamp) && !StringUtils.isEmpty(nonce)){
            List<String> params = new ArrayList<String>();  
            params.add(Config.token);  
            params.add(timestamp);  
            params.add(nonce);
            
            //1. 将token、timestamp、nonce三个参数进行字典序排序  
            Collections.sort(params, new Comparator<String>() {
                @Override  
                public int compare(String o1, String o2) {  
                    return o1.compareTo(o2);  
                }  
            });  
            //2. 将三个参数字符串拼接成一个字符串进行sha1加密  
            String tmpStr = SecretUtil.Sha1Encode(params.get(0) + params.get(1) + params.get(2));
            if(signature.equals(tmpStr)){
                return true;
            }else{
                return false;
            }
        }
        return false;
    }
}
